package tutorial.java.swing;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;

import org.omg.CORBA.PUBLIC_MEMBER;

public class CustomProgressBar extends JFrame {

	JProgressBar pro1 = new JProgressBar();
	JButton jButton1 = new javax.swing.JButton("Run");

	public CustomProgressBar() {
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setSize(300, 70);
		this.pro1.setStringPainted(true);
		this.pro1.setLocation(0, 100);
		addListenerToRunButton();
		JPanel panel = new JPanel();
		panel.add(this.jButton1);
		panel.add(this.pro1);
		this.add(panel);
		this.setVisible(true);
	}

	private void addListenerToRunButton() {
		this.jButton1.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				ProgressBarSwingWorker progressBarSwingWorker = new ProgressBarSwingWorker();
				progressBarSwingWorker
						.addPropertyChangeListener(new PropertyChangeListener() {
							@Override
							public void propertyChange(PropertyChangeEvent e) {
								if (e.getPropertyName().equals("progress"))
									pro1.setValue((Integer) e.getNewValue());
							}
						});
				progressBarSwingWorker.execute();
			}
		});
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new CustomProgressBar();
	}
}

class ProgressBarSwingWorker extends SwingWorker<Object, Object> {
	@Override
	protected Object doInBackground() throws Exception {
		final int N = 1000;
		for (int i = 1; i < N; i++) {
			Thread.sleep(10);
			int percent = 100 * i / N + 1;
			this.setProgress(percent);
		}
		return null;
	}
}
